
const db = uniCloud.database();
const collection1 = db.collection('ha_report_list');
const collection2 = db.collection('ha_report_record');
const collection3 = db.collection('ha_group_person');

async function checkReportRecord(report_id,gp_id) {
	let res1 = await collection1
		.doc(report_id)
		.get();

	if (res1.data && res1.affectedDocs === 1) {
	} else {
		return false
	}

	let res2 = await collection2
		.where({
			report_id,
			gp_id
		})
		.orderBy("create_time", "desc")
		.limit(1)
		.get();

	if (res2.data && res2.affectedDocs >= 1) {
		if (res2.data[0].allow_modify === 1) {
			return true;
		}

		// 检查间隔时间 TODO
		// res1.data[0].interval_hour

		return false;
	}

	return true;
}

async function getOneRecord(record_id) {
	let res2 = await collection2
		.doc(record_id)
		.get();

	if (res2.data && res2.affectedDocs === 1) {
	} else {
		return false;
	}

	if (res2.data[0].hasOwnProperty('report_id') == false) {
		return false;
	}

	let res1 = await collection1
		.doc(res2.data[0].report_id)
		.get();

	if (res1.data && res1.affectedDocs === 1) {
	} else {
		return false;
	}

	return {
		schema: res1.data[0].content,
		model: res2.data[0].model
	}
}

async function getReportRecord(report_id,condition = {}) {
	let res2 = await collection2
		.where(
			Object.assign({
				report_id
			},condition)
		)
		.orderBy("create_time", "asc")
		.get();

	if (res2.data && res2.affectedDocs >= 1) {
	} else {
		return false;
	}

	let recordList = [];
	for (var i = 0; i < res2.data.length; i++) {
		let res3 = await collection3
			.doc(
				res2.data[i].gp_id
			)
			.get();

		recordList.push(
			Object.assign({
				person_name: res3.data[0].person_name,
				person_identity: res3.data[0].person_identity
			},
			res2.data[i].model
			)
		);
	}

	return recordList;
}

export default {
	checkReportRecord,
	getOneRecord,
	getReportRecord
}